import base from './base'
import wepy from 'wepy'
/**
 * 授权服务类
*/
export default class auth extends base {
  // 一键登录
  static async login() {
    const openId = this.getConfig('open_id')
    // 判断sessionKey是否过期
    const isKeyGood = await this.isKeyGood()
    if (openId === '' || !isKeyGood) {
      // debugger
      // 多个页面调用本函数，保证只调用一次
      const { flag } = await this.isNewUser() // 是否是新用户
      this.setConfig('isNewUser', flag)
      await this.doLogin()
    }
  }
  // 判断sessionKey有效期
  static async isKeyGood() {
    return new Promise((resolve, reject) => {
      wx.checkSession({success() {
        resolve(true)
      },
        fail () {
          resolve(false)
        }
      })
    })
  }
  /**
   * 执行登录操作
   */
  static async doLogin() {
    const {code} = await wepy.login()
    await this.setConfig('code', code)
    const { openId, sessionKey } = await this.getOpenId(code)
    await this.setConfig('open_id', openId)
    await this.setConfig('sessionKey', sessionKey)
    await this.login()
  }

  /**
   * 读取权限值
   */
  static getConfig(key) {
    return wx.getStorageSync(key)
  }

  /**
   * 检查是否存在权限制
   */
  static hasConfig(key) {
    const value = this.getConfig(key)
    return value != null && value !== ''
  }

  /**
   * 设置权限值
   */
  static async setConfig(key, value) {
    await wepy.setStorage({key: key, data: value})
    // wepy.$instance.globalData.auth[key] = value
  }

  /**
   * 获取openid
   * @param {*} code
   */
  static async getOpenId (code) {
    const url = this.baseUrl + `/v2/user/openId.get/${code}`
    return this.get(url)
  }
  static async saveUserInfo(detail) {
    const url = this.baseUrl + `/v2/user/user.save`
    const {encryptedData, iv} = detail
    const param = {
      encryptedData,
      iv,
      'wxCode': '1',
      'sessionKey': this.getConfig('sessionKey'),
      'openId': this.getConfig('open_id')
    }
    return this.post(url, param)
  }
  static async isNewUser() {
    const {code} = await wepy.login()
    const url = this.baseUrl + `/clientUser/isNewUser`
    const param = {code}
    return this.post(url, param)
  }
}
